package com.ricervcvcer.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ricervcvcer.common.util.ResultEntity;
import com.ricervcvcer.user.entity.SysRoleRight;
import com.ricervcvcer.user.service.ISysRoleRightService;
import com.ricervcvcer.user.util.RicervcvcerConstant;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author moge
 * @since 2022-01-10
 */
@RestController
@RequestMapping("sys-role-right")
public class SysRoleRightController {
    @Autowired
    ISysRoleRightService roleRightService;

    @ApiOperation("根据角色id获取对应的菜单id")
    @GetMapping("getByRoleId/{id}")
    public ResultEntity getByRoleId(@ApiParam("角色id") @PathVariable Integer id){
        QueryWrapper qw=new QueryWrapper();
        qw.eq("rf_role_id",id);
        List<SysRoleRight> list = roleRightService.sellist(qw);
        return ResultEntity.successWithData(list);
    }
    @ApiOperation("重新给对应的角色分配菜单权限")
    @PutMapping("ids/{roleId}")
    @Transactional
    public ResultEntity update(
            @PathVariable Integer roleId,
            @RequestBody List<String> rightIds){
        // 删除原来的权限
        Map<String,Object> map=new HashMap<>();
        map.put("rf_role_id", roleId);
        boolean b1 = roleRightService.removeByMap(map);
        // 把新权限添加
        List<SysRoleRight> srs = rightIds.stream().map((item) -> {
            SysRoleRight s = new SysRoleRight();
            s.setRfRoleId(roleId);
            s.setRfRightCode(item);
            return s;
        }).collect(Collectors.toList());

        boolean b2 = roleRightService.saveBatch(srs);
        if(!(b1 && b2)){
            throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
        }
        return ResultEntity.successWithoutData();
    }
}
